﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using WeatherAggregator;

namespace WebUi.Web
{

	/// <summary>
	/// Объект для передачи данных о погоде в апплет
	/// </summary>
    [DataContract]
    public class WeatherDto
    {
        private static readonly Dictionary<PropertyInfo, PropertyInfo> PropMapping;

        static WeatherDto()
        {
			// подготовка зеркалированных данных для мэппинга. 
            var dtoProperties =
                typeof(WeatherDto).GetProperties(BindingFlags.SetProperty | BindingFlags.Public | BindingFlags.Instance);
            var dbProperties =
                typeof (WeatherDataEntry).GetProperties(BindingFlags.GetProperty | BindingFlags.Public |
                                                        BindingFlags.Instance);

            var propMapping = from p in dtoProperties
                              join dbp in dbProperties on p.Name equals dbp.Name
                              select new {dto = p, db = dbp};

            PropMapping = propMapping.ToDictionary(_ => _.dto, _ => _.db);
        }

        public WeatherDto(WeatherDataEntry dbEntry)
        {
            foreach (var prop in PropMapping)
            {
                var val = prop.Value.GetValue(dbEntry, null);
                prop.Key.SetValue(this, val, null);
            }
        }

		[Display(Name ="№")]
        [DataMember]
        public Int32 Id { get; set; }

		[Display(Name = "Город")]
        [DataMember]
        public string CityName { get; set; }

		[Display(Name = "Время")]
		[DisplayFormat(DataFormatString = "{0:g}")]
        [DataMember]
        public DateTimeOffset TimeUtc { get; set; }

		[Display(Name = "Температура")]
        [DataMember]
        public decimal Temperature { get; set; }

        [DataMember]
        public string Precipitation { get; set; }

        [DataMember]
        public string SourceId { get; set; }

    }
}